package com.zzccyy.jpdemo.utils;

import android.os.Handler;
import android.os.Looper;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * OkHttp网络请求工具类（单例模式）
 */
public class HttpUtils {
    // 超时时间（10秒）
    private static final int TIME_OUT = 10;
    private static HttpUtils mInstance;
    private OkHttpClient mClient;
    // 主线程Handler（用于将回调切换到主线程）
    private Handler mMainHandler;

    // 私有构造方法（单例模式）
    private HttpUtils() {
        // 初始化OkHttpClient
        mClient = new OkHttpClient.Builder()
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();

        // 初始化主线程Handler
        mMainHandler = new Handler(Looper.getMainLooper());
    }

    // 获取单例实例
    public static synchronized HttpUtils getInstance() {
        if (mInstance == null) {
            mInstance = new HttpUtils();
        }
        return mInstance;
    }

    /**
     * GET请求
     *
     * @param url      请求地址
     * @param params   请求参数（可为null）
     * @param callback 回调接口
     */
    public void get(String url, Map<String, String> params, final HttpCallback callback) {
        // 拼接参数到URL
        String finalUrl = url;
        if (params != null && !params.isEmpty()) {
            finalUrl += "?";
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue())
                        .append("&");
            }
            String paramStr = sb.toString();
            // 移除最后一个&
            paramStr = paramStr.substring(0, paramStr.length() - 1);
            finalUrl += paramStr;
        }

        // 构建请求
        Request request = new Request.Builder()
                .url(finalUrl)
                .get() // 默认就是GET请求，可省略
                .build();

        // 执行异步请求
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 切换到主线程回调
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onFailure("请求失败：" + e.getMessage());
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                try {
                    final String result = response.body().string();
                    // 切换到主线程回调
                    mMainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                if (response.isSuccessful()) {
                                    callback.onSuccess(result);
                                } else {
                                    callback.onFailure("请求失败，code：" + response.code());
                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    mMainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFailure("解析响应失败：" + e.getMessage());
                            }
                        }
                    });
                } finally {
                    // 关闭响应体
                    if (response.body() != null) {
                        response.body().close();
                    }
                }
            }
        });
    }

    /**
     * POST请求（表单提交）
     *
     * @param url      请求地址
     * @param params   请求参数（可为null）
     * @param callback 回调接口
     */
    public void post(String url, Map<String, String> params, final HttpCallback callback) {
        // 构建表单参数
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formBuilder.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody formBody = formBuilder.build();

        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        // 执行异步请求（与GET逻辑一致）
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mMainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callback != null) {
                            callback.onFailure("请求失败：" + e.getMessage());
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                try {
                    final String result = response.body().string();
                    mMainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                if (response.isSuccessful()) {
                                    callback.onSuccess(result);
                                } else {
                                    callback.onFailure("请求失败，code：" + response.code());
                                }
                            }
                        }
                    });
                } catch (final Exception e) {
                    mMainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callback != null) {
                                callback.onFailure("解析响应失败：" + e.getMessage());
                            }
                        }
                    });
                } finally {
                    if (response.body() != null) {
                        response.body().close();
                    }
                }
            }
        });
    }

    /**
     * POST请求（JSON格式提交）
     *
     * @param url        请求地址
     * @param jsonParams JSON格式的参数（Map转JSON）
     * @param callback   回调接口
     */
    public void postJson(String url, Map<String, String> jsonParams, final HttpCallback callback) {
        try {
            // 1. 将Map参数转换为JSON字符串
            JSONObject jsonObject = new JSONObject();
            if (jsonParams != null && !jsonParams.isEmpty()) {
                for (Map.Entry<String, String> entry : jsonParams.entrySet()) {
                    jsonObject.put(entry.getKey(), entry.getValue());
                }
            }
            String jsonStr = jsonObject.toString();

            // 2. 创建JSON类型的请求体（指定Content-Type为application/json）
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody requestBody = RequestBody.create(JSON, jsonStr);

            // 3. 构建请求（使用JSON请求体）
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody) // 使用JSON请求体
                    .build();

            // 4. 执行异步请求（与之前逻辑一致）
            mClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    mMainHandler.post(() -> {
                        if (callback != null) {
                            callback.onFailure("请求失败：" + e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    try {
                        final String result = response.body().string();
                        mMainHandler.post(() -> {
                            if (callback != null) {
                                if (response.isSuccessful()) {
                                    callback.onSuccess(result);
                                } else {
                                    callback.onFailure("请求失败，code：" + response.code());
                                }
                            }
                        });
                    } catch (final Exception e) {
                        mMainHandler.post(() -> {
                            if (callback != null) {
                                callback.onFailure("解析响应失败：" + e.getMessage());
                            }
                        });
                    } finally {
                        if (response.body() != null) {
                            response.body().close();
                        }
                    }
                }
            });

        } catch (JSONException e) {
            // JSON转换失败时的回调
            mMainHandler.post(() -> {
                if (callback != null) {
                    callback.onFailure("参数转换JSON失败：" + e.getMessage());
                }
            });
        }
    }

    /**
     * 网络请求回调接口
     */
    public interface HttpCallback {
        // 请求成功回调（主线程）
        void onSuccess(String result);

        // 请求失败回调（主线程）
        void onFailure(String errorMsg);
    }
}